package com.natalia.file.verify;

import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidatorContext;

/**
 * @Author yang
 **/
public class FileValid{


    public static  boolean isFileInvalid(MultipartFile file, long maxSize, ConstraintValidatorContext context) {
        if (file == null || file.isEmpty()) {
            return addViolation(context, "file cannot be empty");
        }
        if (file.getSize() > maxSize * 1024 * 1024) {
            return addViolation(context, String.format("the file size exceeds %d MB", maxSize));
        }
        return false;
    }

    public static boolean addViolation(ConstraintValidatorContext context, String message) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        return true;
    }
}
